using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Tycho.Lexer;
using Tycho.Parser;
using Tycho.Parser.Tokens;
using Tycho.Runtime;

namespace Tycho.Language {
    class ExpressionSourceParser : ISourceParser {
        readonly IParser ExpressionParser;

        public ExpressionSourceParser (AnyObject macroContext) {
            ExpressionParser = GetExpressionParser (macroContext);
        }

        public AnyObject Parse (string expression, string filename) {
            List<Token> tokens = NativeLexer.Lex (expression, filename);
            return ExpressionParser.Parse (tokens, true);
        }

        static IParser GetExpressionParser (AnyObject macroContext) {
            var plang = new ParserLanguage ();
            plang.MacroBuilder = new MacroBuilder (macroContext);
            plang.TokensParser = new TokenListParser ();
            plang.MacroParser = GetParser ("Tycho.Language.macro-expression.language", "expression", new ParserLanguage ());
            return GetParser ("Tycho.Language.expression.language", "expression", plang);
        }

        static IParser GetParser (string resource, string parser, ParserLanguage plang) {
            Assembly assembly = typeof (ExpressionLanguage).Assembly;
            var resourceStream = assembly.GetManifestResourceStream (resource);
            var file = new StreamReader (resourceStream);
            return plang.BuildParsers (file.ReadToEnd (), parser) [parser];
        }
    }
}